#include "QMoveEdgeOperation.h"

#include "Core/MainWindow.h"
#include <QMessageBox>
#include "Core/RWGeometryTool.h"
#include <TopoDS.hxx>
#include "FeatureShape/ShapeOperation.h"
#include "FeatureShape/HistoryManager.h"

QMoveEdgeOperation::QMoveEdgeOperation(MainWindow* inMainWindow, ShapeOperation* inOperation, QWidget* parent)
	: QRSWidgetBase(inMainWindow, inOperation, parent)
	, ui(new Ui::QMoveEdgeOperationClass())
{
	ui->setupUi(this);

	m_mainWindow->SetCanMultiSelect(false);

	connect(ui->modifyButton, &QPushButton::clicked, this, &QMoveEdgeOperation::OnModify);
	connect(ui->confirmButton, &QPushButton::clicked, this, &QMoveEdgeOperation::OnConfirm);
	connect(ui->cancelButton, &QPushButton::clicked, this, &QMoveEdgeOperation::close);

	connect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QMoveEdgeOperation::OnSelectedSubShapes);

	m_mainWindow->SetSelectionMode(SM_Edge);
}

QMoveEdgeOperation::~QMoveEdgeOperation()
{
	delete ui;
}

void QMoveEdgeOperation::OnSelectedSubShapes(QIVtkSelectionPipeline* actor)
{
	if (actor)
	{
		m_selectedActor = actor;
	}
}

void QMoveEdgeOperation::closeEvent(QCloseEvent* event)
{
	disconnect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QMoveEdgeOperation::OnSelectedSubShapes);

	m_mainWindow->SubWidgetClose(bIsConfirmed);
	m_mainWindow->SetCanMultiSelect(true);
}

void QMoveEdgeOperation::OnModify()
{
	MoveEdgeInner();
	m_selectedActor = nullptr;
}

void QMoveEdgeOperation::OnConfirm()
{
	MoveEdgeInner();
	close();
}

void QMoveEdgeOperation::MoveEdgeInner()
{
	if (!m_selectedActor)
	{
		QMessageBox::warning(this, tr("Warning"), tr("Please select a valid shape."));
		return;
	}

	TopoDS_Edge edge = TopoDS::Edge(m_mainWindow->GetSelectedShapes()[0]);
	TopoDS_Shape newShape = OffsetEdgeInPlanarShape(m_selectedActor->OccShape(), edge, ui->len->value());

	if (newShape.IsNull())
	{
        QMessageBox::warning(this, tr("Warning"), tr("Failed to move edge."));
        return;
	}

	int shapeIndex = GetIndexFromActor(m_mainWindow->GetCachedActors(), m_selectedActor);
	int subShapeIndex = GetSubShapeIndex(m_selectedActor->OccShape(), TopAbs_EDGE, edge);

	MoveEdgeOperation* op = new MoveEdgeOperation(QString("Move Edge"), shapeIndex, subShapeIndex, ui->len->value());
	m_mainWindow->GetHistoryManager()->applyOperation(op);

	m_mainWindow->RemoveActorFromRenderer(m_selectedActor);
	m_mainWindow->createBasicUnitActor(newShape, true);
}
